import { defineConfig, loadEnv, PluginOption } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import { createHtmlPlugin } from 'vite-plugin-html';
import vueJsx from '@vitejs/plugin-vue-jsx';

const getViteEnv = (mode, target) => {
  return loadEnv(mode, process.cwd())[target];
};
export default defineConfig(({ mode }) => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const VITE_BASE_URL = env.VITE_BASE_URL;
  return {
    plugins: [
      vue() as PluginOption,
      vueJsx() as unknown as PluginOption,
      createHtmlPlugin({
        inject: {
          data: {
            title: getViteEnv(mode, 'VITE_TITLE')
          }
        }
      }) as PluginOption
    ] as PluginOption[],
    resolve: {
      alias: [
        {
          find: /\/@\//,
          replacement: pathResolve('src') + '/'
        },
        {
          find: /\/#\//,
          replacement: pathResolve('types') + '/'
        }
      ]
    },
    server: {
      proxy: {
        '/api': {
          target: VITE_BASE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    }
  };
});

function pathResolve(dir: string) {
  return resolve(process.cwd(), '.', dir);
}
